package com.amiu.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.amiu.shiro.db.user.User;
import com.amiu.shiro.db.user.UserDao;
import com.amiu.util.Result;
import com.amiu.util.ResultUtil;

@RestController
public class LoginController {
	@Autowired UserDao dao;
	
	@RequestMapping("/login")
    public Result loginPost(@RequestBody User loginUser) {
		String username=loginUser.getUsername();
		String password = loginUser.getPassword();
		dao.findByName(username);
        if (username == null || username == "") {
            throw new RuntimeException("用户名不能为空");
        }
        if (password == null || password == "") {
            throw new RuntimeException("密码不能为空");
        }
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            user.login(token);
            return new ResultUtil().renderSuccess("登录成功！");
        } catch (UnknownAccountException e) {
        	return new ResultUtil().renderFail("账号不存在！");
        } catch (DisabledAccountException e) {
        	return new ResultUtil().renderFail("账号未启用！");
        } catch (IncorrectCredentialsException e) {
        	return new ResultUtil().renderFail("密码错误！");
        }catch (ExcessiveAttemptsException e) {
        	//登录失败最大限制次数
        	return new ResultUtil().renderFail(e.getMessage());
		}catch (Throwable e) {
        	return new ResultUtil().renderFail("未知错误："+e.getMessage());
        }
    }

	@RequestMapping("/logout")
	public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        if(subject == null)
        	return new ResultUtil().renderFail("您还未登录");
//        User user = (User) subject.getPrincipal();
//        System.out.println(user);
        subject.logout();
        return new ResultUtil().renderSuccess();
    }
	
	/**
     * 未授权
     * @return {String}
     */
    @RequestMapping("/unauth")
    public String unauth() {
        if (SecurityUtils.getSubject().isAuthenticated() == false) {
            return "redirect:/login";
        }
        return "unauth";
    }
	
}
